package com.wjjun.customview.views;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;

import com.wjjun.customview.R;

/**
 * 高度自适应的imageView
 * Created by 67535 on 2018/7/9.
 */

public class ResizableImageView extends android.support.v7.widget.AppCompatImageView {

    private float maxScale = 0;

    public ResizableImageView(Context context) {
        super(context);
    }

    public ResizableImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    @SuppressLint("CustomViewStyleable")
    private void init(Context context, AttributeSet attributeSet) {
        TypedArray typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.scaleAble);
        maxScale = typedArray.getFloat(R.styleable.scaleAble_maxHeightScale, 0);
        typedArray.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        Drawable d = getDrawable();

        if (d != null) {
            int width = MeasureSpec.getSize(widthMeasureSpec);
            //高度根据使得图片的宽度充满屏幕计算而得
            int height = (int) Math.ceil((float) width * (float) d.getIntrinsicHeight() / (float) d.getIntrinsicWidth());

            int maxHeight = (int) (width * maxScale);
            if (maxHeight > 0 && height > maxHeight) {
                height = maxHeight;
            }

            setMeasuredDimension(width, height + getPaddingBottom() + getPaddingTop());
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }

}
